<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 仓库-门店-人员管理
 * @package app\cms\admin
 */
class StoreUser extends Admin
{
    // 模型初始化
    protected static function init()
    {
        //TODO:初始化内容
    }

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return mixed
     */
    public function index($store_id = [])
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取筛选
        $map = $this->getMap();

        //数据获取
        $data = input();

        // 数据列表
        $data_list = model('ErpStoreUser', 'model') -> where($map)-> where('store_id','=',$store_id) -> order('create_time desc') -> paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('关联人员管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为user_name
            ->setTableName('erp_store_user') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '人员ID'],
                ['user_name', '用户名'],
                ['nick_name', '昵称'],
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearch(['id' => '人员ID', 'user_name' => '用户名', 'nick_name' => '昵称']) // 设置搜索参数
            ->addTopButton('custom', ['title' => '新增', 'href' => url('erp/store_user/add', ['store_id' => $store_id])],true)
            // ->addRightButton('edit', '', ['area' => ['50%', '80%']]) // 批量添加右侧按钮
            ->addRightButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 添加
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($store_id = []){
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post();

            // $user_name      = isset($data['user_name']) ? $data['user_name'] : '';
            // $nick_name  	= isset($data['nick_name']) ? $data['nick_name'] : '';
            // $password  	    = isset($data['password']) ? $data['password'] : '';
            $store_id  		= isset($data['store_id']) ? $data['store_id'] : '';
            $admin_uid  	= isset($data['admin_uid']) ? $data['admin_uid'] : '';
			$admin_user = model('app\user\model\User') -> find($admin_uid);
			$user_name = $admin_user['username'];
			$nick_name = $admin_user['nickname'];
			$password = $admin_user['password'];
			
			if($admin_uid == ''){
				$this->error('请选择关联账号，可联系管理员添加账号');
			}
            //数据验证
            // $Validate = validate('StoreUser', 'validate');
            // if( !$Validate -> scene('storeuser_add') -> check($data) ){
                // $this->error($Validate -> getError());
            // }
            $rel = model('ErpStoreUser','model') -> addData($user_name, $password, $nick_name, $store_id);

            if($rel['code'] == 200){
				$map = [];
				$map['id'] = $admin_uid;
				
				$data = [];
				$data['store_id'] = $store_id;
				$data['store_uid'] = $rel['data'];
				$rel = model('app\user\model\User') -> update($data, $map);
				
                $this->success('新增成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }
		
		$map[] = [
			['role', '=', 6],
			['store_id', '=' , 0],
		];
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增人员') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                // ['text', 'user_name', '用户名','必填'],
                // ['text', 'nick_name', '昵称', '必填，可由英文字母、数字组成'],
                // ['text', 'password', '密码', '请输入密码'],
				['select', 'admin_uid', '关联账号', '请选择关联账号', model('app\user\model\User') -> where($map) -> column('id,nickname')],
            ])->addHidden('store_id',$store_id)
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 仓库id
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['id'] = $id;
            $user_name      = isset($data['user_name']) ? $data['user_name'] : '';
            $password  		= isset($data['password']) ? $data['password'] : '';
            $nick_name  	= isset($data['nick_name']) ? $data['nick_name'] : '';

            //数据验证
            $Validate = validate('StoreUser', 'validate');
            if( !$Validate -> scene('storeuser_add') -> check($data) ){
                $this->error($Validate -> getError());
            }

            $rel = model('ErpStoreUser','model') -> editData($id,$user_name, $password, $nick_name);

            if($rel['code'] == 200){
                $this->success('编辑成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        $info = model('ErpStoreUser', 'model') -> find($id);

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑人员')
            ->addFormItems([
                ['text', 'user_name', '用户名','必填'],
                ['text', 'nick_name', '昵称', '必填，可由英文字母、数字组成'],
                ['text', 'password', '密码', '请输入密码'],
            ])
            ->setFormData($info)
            ->fetch();
    }
	
	public function delete($ids = []){
		$info = model('app\user\model\User') -> where('store_uid', $ids) -> find();
		if(!empty($info)){
			$map = [];
			$map['id'] = $info['id'];
			
			$data = [];
			$data['store_id'] 	= 0;
			$data['store_uid'] 	= 0;
			$res = model('app\user\model\User') ->update($data, $map);
		}
		$res = model('ErpStoreUser') -> destroy($ids);
		$this->success('删除成功');
	}

}